<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Floyd判圈算法（龟兔赛跑算法） | CodeLife</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="问题：如何判断一个链表是否有闭环？
今天看到了这个问题，提到了Floyd判圈算法，于是去查了一下这个算法，把自己的一点想法写下来。">
<meta property="og:type" content="article">
<meta property="og:title" content="Floyd判圈算法（龟兔赛跑算法）">
<meta property="og:url" content="http://jia199474.oschina.io/2015/11/30/floyd-ring/index.html">
<meta property="og:site_name" content="CodeLife">
<meta property="og:description" content="问题：如何判断一个链表是否有闭环？
今天看到了这个问题，提到了Floyd判圈算法，于是去查了一下这个算法，把自己的一点想法写下来。">
<meta property="og:updated_time" content="2016-02-22T08:36:10.237Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Floyd判圈算法（龟兔赛跑算法）">
<meta name="twitter:description" content="问题：如何判断一个链表是否有闭环？
今天看到了这个问题，提到了Floyd判圈算法，于是去查了一下这个算法，把自己的一点想法写下来。">
  
  
    <link rel="icon" href="css/images/favicon.ico">
  
  
 <link href='//fonts.useso.com/css?family=Open+Sans:400italic,400,600' rel='stylesheet' type='text/css'>
 <link href="//fonts.useso.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">


  <link rel="stylesheet" href="/css/style.css" type="text/css">
  <link rel="stylesheet" href="/font-awesome/css/font-awesome.min.css" type="text/css">
  

  <!--

-->
  
</head>
<body>
  <div id="container">
    <header id="header">
  <div id="header-main" class="header-inner">
    <div class="outer">
      <a href="/" id="logo"><i class="logo" style="background-image: url(/css/images/logo.png)"></i><span class="site-title">CodeLife</span></a>
      <nav id="main-nav">
        
          <a class="main-nav-link" href="/.">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
          <a class="main-nav-link" href="/about">About</a>
        
      </nav>
      
        <nav id="sub-nav">
          <div class="profile" id="profile-nav">
            <a id="profile-anchor" href="javascript:;"><img class="avatar" src="/css/images/ava.png"><i class="fa fa-caret-down"></i></a>
          </div>
        </nav>
      
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit"> </button><input type="hidden" name="sitesearch" value="http://jia199474.oschina.io"></form>
      </div>
    </div>
  </div>
  <div id="main-nav-mobile" class="header-sub header-inner">
    <table class="menu outer">
      <tr>
        
          <td><a class="main-nav-link" href="/.">Home</a></td>
        
          <td><a class="main-nav-link" href="/archives">Archives</a></td>
        
          <td><a class="main-nav-link" href="/about">About</a></td>
        
        <td>
          <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><input type="hidden" name="sitesearch" value="http://jia199474.oschina.io"></form>
        </td>
      </tr>
    </table>
  </div>
</header>

    <div class="outer">
      
        <aside id="profile">
  <div class="inner profile-inner">
    <div class="base-info profile-block">
      <img id="avatar" src="/css/images/ava.png">
      <h2 id="name">Zachary Jia</h2>
      <h3 id="title">A programmer</h3>
      <span id="location"><i class="fa fa-map-marker"></i>Beijing, China</span>
      <a id="follow" href="https://github.com/ZacharyJia">关注我</a>
    </div>
    <div class="article-info profile-block">
      <div class="article-info-block">
        17
        <span>文章</span>
      </div>
      <div class="article-info-block">
        13
        <span>标签</span>
      </div>
    </div>
    
    <div class="contact-info profile-block">
      <table class="contact-list">
        <tr>
          
          <td><a href="http://github.com/zacharyjia" target="_blank" title="github"><i class="fa fa-github"></i></a></td>
          
          <td><a href="/atom.xml" target="_blank" title="rss"><i class="fa fa-rss"></i></a></td>
          
        </tr>
      </table>
    </div>
    
    
  </div>
</aside>

      
      <section id="main"><article id="post-floyd-ring" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      Floyd判圈算法（龟兔赛跑算法）
    </h1>
  

        <div class="article-meta">
          
  <div class="article-date">
    <i class="fa fa-calendar"></i>
    <a href="/2015/11/30/floyd-ring/">
      <time datetime="2015-11-30T11:24:35.000Z" itemprop="datePublished">2015-11-30</time>
    </a>
  </div>


          
        </div>
      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
                
        <h2 id="问题：">问题：</h2><p>如何判断一个链表是否有闭环？</p>
<p>今天看到了这个问题，提到了Floyd判圈算法，于是去查了一下这个算法，把自己的一点想法写下来。 </p>
<a id="more"></a>
<h3 id="问题的答案是：">问题的答案是：</h3><p>从链表的头部设置两个指针，p1的步长为1， p2的步长为2，同时向前走，如果p1和p2最终能够相遇，则说明链表是有环的。</p>
<p>检测环的基本思想是非常简单的，可以类比成两个人在跑道上跑。只要有圈，跑的快的那个人就一定能够追上跑得慢的那个人。</p>
<p>另外，还有两个相关的问题，一个是如何求环的长度，另一个是如何求环的起点。</p>
<h3 id="求环的长度">求环的长度</h3><p>这个也能非常简单的想到：</p>
<p>两个人相遇的是时候，一定已经在环上了，然后两个人只要再次在环上接着跑，再次相遇的时候（也就是所谓的套圈），跑的快的那个人就比跑得慢的人整整多跑了一圈，所以环的长度也就出来了。  </p>
<p>用算法来描述，也就是第一次相遇后，p1和p2按照原来的步长继续向前查找，并且记录下两个指针遍历过的节点个数。当两个指针再次相遇的时候，遍历的节点数量差就是环的长度了。</p>
<h3 id="第二个就是求环的起点">第二个就是求环的起点</h3><p>解决方法是把其中的一个指针重置到链表头部，然后两个指针步长都为1，继续向前移动，相遇的位置即为环的起点。</p>
<p>方法的解析如下：<br>首先我们设第一次相遇的时候慢指针走过的节点个数为i，设链表头部到环的起点的长度为m, 环的长度为n，相遇的位置与起点位置距离为k。<br>则可以得到:</p>
<blockquote>
<p>i = m + a * n + k</p>
</blockquote>
<p>其中a为慢指针走的圈数。<br>根据快指针和慢指针的速度关系，我们可以得到另一个式子: </p>
<blockquote>
<p>2 * i = m + b * n + k</p>
</blockquote>
<p>其中b为快指针走的圈数。<br>简单处理得到:</p>
<blockquote>
<p>i = (b - a) * n</p>
</blockquote>
<p>也就是说i是圈长的整数倍。<br>这时将其中一个节点放到起点，然后同时向前走m步时，此时从头部走的指针在m位置。而从相遇位置开始走的指针应该在距离起点<code>i + m</code>, i为圈长整数倍，则该指针也应该在距离起点为m的位置，即环的起点。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://jia199474.oschina.io/2015/11/30/floyd-ring/" data-id="cip19u35d00161sqol0jdug79" class="article-share-link">分享到</a>
      
        <a href="http://jia199474.oschina.io/2015/11/30/floyd-ring/#ds-thread" class="article-comment-link">评论</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/算法/">算法</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2015/12/27/ml-week1/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">
        
          机器学习笔记Coursera——Week 1
        
      </div>
    </a>
  
  
    <a href="/2015/10/11/git-fork-update/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">【转载】Git 怎样保证fork出来的project和原project（上游项目）同步更新</div>
    </a>
  
</nav>


  
</article>

  
  <section id="comments">
    <!-- 多说评论框 start -->
    <div class="ds-thread" data-thread-key="post-floyd-ring" data-title="Floyd判圈算法（龟兔赛跑算法）" data-url="http://jia199474.oschina.io/2015/11/30/floyd-ring/"></div>
    <!-- 多说评论框 end -->
    <!-- 多说公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
    var duoshuoQuery = {short_name:'zacharyjia'};
      (function() {
        var ds = document.createElement('script');
        ds.type = 'text/javascript';ds.async = true;
        ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
        ds.charset = 'UTF-8';
        (document.getElementsByTagName('head')[0] 
         || document.getElementsByTagName('body')[0]).appendChild(ds);
      })();
      </script>
    <!-- 多说公共JS代码 end -->
  </section>
  

</section>
      
        <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul id="recent-post" class="">
        
          <li>
            
            <div class="item-thumbnail">
              <a href="/2016/05/17/mysql-new-user-cannot-login/" class="thumbnail">
  
    <span style="background-image:url(http://7xn2d3.com1.z0.glb.clouddn.com/mysql01.png
)" alt="解决MySQL新建用户后无法登录问题" class="thumbnail-image"></span>
  
</a>
            </div>
            
            <div class="item-inner">
              <p class="item-category"></p>
              <p class="item-title"><a href="/2016/05/17/mysql-new-user-cannot-login/" class="title">解决MySQL新建用户后无法登录问题</a></p>
              <p class="item-date"><time datetime="2016-05-17T11:40:15.000Z" itemprop="datePublished">2016-05-17</time></p>
            </div>
          </li>
        
          <li>
            
            <div class="item-thumbnail">
              <a href="/2016/04/10/peterson-solution-turn-variable/" class="thumbnail">
  
    <span style="background-image:url(http://7xn2d3.com1.z0.glb.clouddn.com/no_turn.png
)" alt="Peterson算法中turn(will_wait)变量的作用" class="thumbnail-image"></span>
  
</a>
            </div>
            
            <div class="item-inner">
              <p class="item-category"></p>
              <p class="item-title"><a href="/2016/04/10/peterson-solution-turn-variable/" class="title">Peterson算法中turn(will_wait)变量的作用</a></p>
              <p class="item-date"><time datetime="2016-04-09T16:00:00.000Z" itemprop="datePublished">2016-04-10</time></p>
            </div>
          </li>
        
          <li>
            
            <div class="item-thumbnail">
              <a href="/2016/03/01/PAT-1052/" class="thumbnail">
  
    <span class="thumbnail-image thumbnail-none"></span>
  
</a>
            </div>
            
            <div class="item-inner">
              <p class="item-category"></p>
              <p class="item-title"><a href="/2016/03/01/PAT-1052/" class="title">PAT 1052 Linked List Sorting (25)</a></p>
              <p class="item-date"><time datetime="2016-03-01T15:50:02.000Z" itemprop="datePublished">2016-03-01</time></p>
            </div>
          </li>
        
          <li>
            
            <div class="item-thumbnail">
              <a href="/2016/02/29/PAT-1051/" class="thumbnail">
  
    <span class="thumbnail-image thumbnail-none"></span>
  
</a>
            </div>
            
            <div class="item-inner">
              <p class="item-category"></p>
              <p class="item-title"><a href="/2016/02/29/PAT-1051/" class="title">PAT 1051 Pop Sequence (25)</a></p>
              <p class="item-date"><time datetime="2016-02-29T12:55:35.000Z" itemprop="datePublished">2016-02-29</time></p>
            </div>
          </li>
        
          <li>
            
            <div class="item-thumbnail">
              <a href="/2016/02/29/PAT-1048/" class="thumbnail">
  
    <span class="thumbnail-image thumbnail-none"></span>
  
</a>
            </div>
            
            <div class="item-inner">
              <p class="item-category"></p>
              <p class="item-title"><a href="/2016/02/29/PAT-1048/" class="title">PAT 1048 Find Coins (25)</a></p>
              <p class="item-date"><time datetime="2016-02-29T12:20:58.000Z" itemprop="datePublished">2016-02-29</time></p>
            </div>
          </li>
        
      </ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/life/">life</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/安全/">安全</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/编程/">编程</a><span class="category-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Java/">Java</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/MySQL/">MySQL</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/NSCTF/">NSCTF</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/PAT/">PAT</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/">git</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/life/">life</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/多线程/">多线程</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/安全/">安全</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/总结/">总结</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/机器学习/">机器学习</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/汇编/">汇编</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/笔记/">笔记</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/算法/">算法</a><span class="tag-list-count">7</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap widget-list">
    <h3 class="widget-title">链接</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="http://blog.zacharyjia.me">乱七八糟的想法</a>
          </li>
        
          <li>
            <a href="http://www.icodeyou.com/">牛逼的学长</a>
          </li>
        
      </ul>
    </div>
  </div>


  
  <div id="toTop" class="fa fa-chevron-up"></div>
</aside>
      
    </div>
    <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2015 - 2016 Zachary Jia<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>. Theme by <a href="http://github.com/ppoffice">PPOffice</a>
    </div>
  </div>
</footer>
    

<script type="text/javascript">
  var duoshuoQuery = {short_name:"zacharyjia"};
  (function() {
    var ds = document.createElement('script');
    ds.type = 'text/javascript';ds.async = true;
    ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
    ds.charset = 'UTF-8';
    (document.getElementsByTagName('head')[0] 
     || document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
</script>



 <script src="http://libs.baidu.com/jquery/2.1.3/jquery.min.js"></script>




  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>